package org.kisekiproject.course {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import org.kisekiproject.evaluator.IFunction;
	import org.kisekiproject.events.KisekiEvent;
	import org.kisekiproject.objectset.ObjectSet;

	/**
	 * Query function to extract information from a course.
	 */
	public class CourseQueryFunction extends EventDispatcher implements IFunction {
		private var _course:CourseModel;
		private var _queryString:String="";
		private var _pages:Array;

		/**
		 * Constructor.
		 */
		public function CourseQueryFunction(course:CourseModel) {
			_course=course;
		}

		/**
		 * Set arguments.
		 */
		public function set arguments(value:Array):void {
			if (value.length!=1)
				throw new Error("The $ function should take 1 variable");

			_queryString=value[0];
			_pages=null;
		}

		/**
		 * Get value.
		 */
		public function get value():Object {
			if (!_pages) {
				_pages=_course.getMatchingPages(_queryString);

				trace("matching pages for query: "+_pages.length);

				for each (var p:CoursePage in _pages) {
					trace("have matching page...");
					p.displayObject.addEventListener(KisekiEvent.OUTPUT_CHANGE,onPageOutputChange);
				}
			}

			var a:Array=new Array();

			for each (var q:CoursePage in _pages)
				a.push(q.displayObject);

			return new ObjectSet(a);
		}

		/**
		 * Page output change.
		 */
		private function onPageOutputChange(e:Event):void {
			dispatchEvent(new Event(Event.CHANGE));
		}
	}
}